const { Worker, isMainThread, parentPort, workerData } = require('worker_threads')

let g = 0

const seqArr = [44, 42, 43, 44, 44, 42, 43, 44]

function fibonacci (n) {
  return n === 0
    ? 0
    : n === 1
      ? 1
      : fibonacci(n - 1) + fibonacci(n - 2)
}

function calculate (seq, taskId) {
  return new Promise((resolve, reject) => {
    console.log(`Task ${taskId} starts calculating.`)
    const start = Date.now()
    const result = fibonacci(seq)
    console.log(`The result of task ${taskId} is ${result}, taking ${Date.now() - start} ms.`)
    return resolve(result)
  })
}

let startJob = async () => {
  console.time('main')
  const results = await Promise.all(seqArr.map(calculate))
  results.forEach((result, index) => console.log(`Task ${index}'s result is ${result}`))
  console.timeEnd('main')
}

let startSingleJob = async (id) => {
  console.time('child_' + id)
  const result = await calculate(seqArr[id], id)
  console.log(`Task ${id}'s result is ${result}`)
  console.timeEnd('child_' + id)
}



if (isMainThread) {
  // startJob()
  let finished = 0
  console.time("main")
  for (let i = 0; i < 8; i++) {
    let worker = new Worker(__filename, {workerData: {id: i}})
    worker.on("message", (message) => {
      finished++
      if (finished >= 8 ) {
        console.timeEnd("main")
      }
    })
  }
} else {
  startSingleJob(workerData.id).then(() => {
    parentPort.postMessage("end")
  })
}